package com.example.asus.practice;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

public class Progressbar extends AppCompatActivity {

    private ProgressBar progressbar;
    private int mProgress = 0;
    private  Handler mhandler  = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 0){
                progressbar.setProgress(mProgress);
            }else{
                Toast.makeText(Progressbar.this, "加载完成", Toast.LENGTH_SHORT).show();
                progressbar.setVisibility(View.INVISIBLE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_progressbar);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        progressbar = (ProgressBar)findViewById(R.id.pb);

        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    mProgress = doWork(mProgress);
                    Message msg = new Message();
                    if(mProgress < 100){
                        msg.what = 0;
                        mhandler.sendMessage(msg);
                    }else{
                        msg.what = 1;
                        mhandler.sendMessage(msg);
                        break;
                    }
                }
            }
        }).start();
    }

    private int doWork(int mProgress) {
        mProgress = (int)(mProgress + Math.random()*10);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return mProgress;
    }
}
